/*
 * 這是行列查碼程式用來取得對照檔並存入記憶體中的class
 * author:Blackdiz
 * date:2013/1/19
 * version:0.1beta
 * 
 * date:2013/1/26
 * comment:新增keyMapping.properties放置字母和行列字根的對應表以在介面上呈現行列數字
 * 排列而不是直接呈呈現數字
 * version:0.2beta
 */
package com.arrayutil.model;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ArrayUtilM {
	// 把對照檔以<字,List<碼>>的結構儲存
	private Map<String, List<String>> wordMap = new HashMap<String, List<String>>();
	private Properties keyMapping = new Properties();
	
	public ArrayUtilM() {
		getProperties();
		getDictionary();
	}

	//讀入keyMapping.properties
	private void getProperties() {
		try {
			keyMapping.load(new FileReader("res/keyMapping.properties"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	// 用來從對照檔中取得字和行列碼的對應
	private void getDictionary() {
		BufferedReader br = null;
		try {
			// 由於對照檔使用UTF-16編碼，所以必須用InputStreamReader指定讀入時的編碼
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					"res/array30_27489.txt"), "UTF-16"));

			String s = null; 
			while ((s = br.readLine()) != null) {
				splitWord(s);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 將字和行列碼以<字，碼>的方式存入Map
	private void saveToMap(String[] wordAndCode) {
		StringBuilder newCodes = new StringBuilder();
		if (wordMap.containsKey(wordAndCode[1])) {
			for(int i = 0; i < wordAndCode[0].length(); i++) {
				String newCode = keyMapping.getProperty(String.valueOf(wordAndCode[0].charAt(i)));
				newCodes.append(newCode);
			}
			wordMap.get(wordAndCode[1]).add(newCodes.toString());
		} else {
			for(int i = 0; i < wordAndCode[0].length(); i++) {
				String newCode = keyMapping.getProperty(String.valueOf(wordAndCode[0].charAt(i)));
				newCodes.append(newCode);
			}
			List<String> codeList = new ArrayList<String>();
			codeList.add(newCodes.toString());
			wordMap.put(wordAndCode[1], codeList);
		}
	}

	// 把對照檔中每一行的字和碼分開
	private void splitWord(String word) {
		String[] wordAndCode = word.split("\t");

		saveToMap(wordAndCode);
	}

	public List<String> queryCodes(String queryWord) {
		List<String> code = wordMap.get(queryWord);

		return code;
	}
}